﻿using Infrastructure.DbUtility;
using Infrastructure.Utility;
using System;
using System.Data;

public partial class admin_grade_edit : BasePage
{


    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack) this.InitGrade(Request["k"]);
        if (Request["do"] == "save") this.SaveData();
    }

    /// <summary>
    /// 保存数据
    /// </summary>
    private void SaveData()
    {
        UploadHelper helper = new UploadHelper();
        DataRow fileRow = null;
        foreach (string k in Request.Files)
        {
            if (Request.Files[k] == null || Request.Files[k].InputStream == null || Request.Files[k].InputStream.Length == 0) continue;
            fileRow = helper.Upload(Request.Files[k], true);
            break;
        }

        var nid = int.Parse(Request["nid"]);
        var name = Request["name"];
        var description = Request["description"];
        var ismenu = Request["ismenu"] == "true";
        var menuindex = int.Parse(Request["menuindex"]);
        var creator = int.Parse(Request["creator"]);
        var systime = DateTime.Parse(Request["systime"]);
        var status = int.Parse(Request["status"]);

        if (nid == 0)
        {
            creator = 1;//预留，后续完善。
            systime = DateTime.Now;
            status = 1;//默认有效
        }

        string sql = string.Empty;

        if (nid <= 0)
        {
            // 新增
            sql = @"INSERT INTO Grade (name,description,ismenu,menuindex,creator,systime,status,[image]) 
                         VALUES({0},{1},{2},{3},{4},{5},{6},{7}) SELECT @@identity";
        }
        else
        {
            sql = @"UPDATE Grade SET name = {0},description={1},ismenu={2},menuindex={3},creator={4},systime={5},status={6},[image]={7} 
                          WHERE nid = {8} SELECT {8}";
        }

        DbHelper db = new DbHelper();
        Entity["nid"] = db.ExecuteScalarEx(sql, name, description, ismenu, menuindex, creator, systime, status, fileRow.Value("fullPath") ?? string.Empty, nid);

        Response.Clear();
        Response.Write("{\"success\":true}");
        Response.End();
    }

    /// <summary>
    /// 初始化表单
    /// </summary>
    /// <param name="p"></param>
    private void InitGrade(string snid)
    {
        int nid = 0;
        if (!int.TryParse(snid, out  nid) && nid <= 0) return;

        string sql = "SELECT * FROM Grade (NOLOCK) WHERE nid = {0}";

        DbHelper db = new DbHelper();
        var table = db.ExecQueryEx(sql, nid);

        if (table == null || table.Rows.Count == 0) return;
        foreach (DataColumn col in table.Columns) Entity[col.ColumnName] = table.Rows[0][col];
    }
}